﻿using System;
using System.Collections.Generic;

using RexToy.UI.WinForm.Pmlx;
using RexToy.UI.WinForm.ViewModel;

namespace RexToy.UI.WinForm.Controls
{
    public class TextBox : System.Windows.Forms.TextBox, IDataExchange
    {
        public TextBox()
        {
            this._updateModelTrigger = UpdateModelTrigger.LostFocus;
            this._exchange = true;
        }

        public void UpdateModel(ViewModelBase model)
        {
            if (this.ReadOnly)
                return;

            IReflector r = Reflector.Bind(model);
            if (!string.IsNullOrEmpty(Text))
            {
                object val = TypeCast.ChangeToTypeOrNullableType(Text, r.GetPropertyType(BindPropertyName));
                r.SetPropertyValue(BindPropertyName, val);
            }
        }

        public void UpdateView(ViewModelBase model)
        {
            IReflector r = Reflector.Bind(model);
            object val = r.GetPropertyValue(BindPropertyName);
            if (val != null)
                this.Text = val.ToString();
            else
                this.Text = string.Empty;
        }

        protected override void OnLostFocus(EventArgs e)
        {
            this.UpdateModelByTrigger(UpdateModelTrigger.LostFocus);
            base.OnLostFocus(e);
        }

        protected override void OnTextChanged(EventArgs e)
        {
            this.UpdateModelByTrigger(UpdateModelTrigger.PropertyChanged);
            base.OnTextChanged(e);
        }

        private string _bindPorpertyName;
        public string BindPropertyName
        {
            get
            {
                return this.GetBindProperty(_bindPorpertyName);
            }
            set
            {
                _bindPorpertyName = value;
            }
        }

        private UpdateModelTrigger _updateModelTrigger;
        public UpdateModelTrigger UpdateModelTrigger
        {
            get { return _updateModelTrigger; }
            set { _updateModelTrigger = value; }
        }

        private bool _exchange;
        public bool Exchange
        {
            get { return _exchange; }
            set { _exchange = value; }
        }
    }
}
